package logging;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author paul jaklitsch, 
 * Code partially taken from 
 * http://www.bitworld.de/index.php/java/javahowto/1-dynamicproxy1
 * 
 * Class, called by the Proxy object in order to log method name, arguments and return value
 * of the business method the client calls
 *
 */
public class LogHandler implements InvocationHandler {

	private Object object;
	private Logger logger = LoggerFactory.getLogger("logging.LogHandler");
	
	public LogHandler(Object object) {
		this.object = object;
	}
	
	@Override
	public Object invoke(Object proxyObject, Method method, Object[] args) throws Throwable {
		logger.debug("calling " + method.getName() + " with parameters: " + method.getParameterTypes());
		
		int paramIndex = 0;
		Class paramTypesArray[] = method.getParameterTypes();
		if (args != null) {
			for (Object currentArgument : args) {
				logger.debug("Argument: " + paramTypesArray[paramIndex].getName());
				logger.debug("Value: " + currentArgument.getClass().cast(currentArgument).toString());
				paramIndex++;
			}			
		}
		
		Object result = method.invoke(this.object, args);
		
		logger.debug("return value: " + (result != null  ? result.getClass().cast(result).toString() : "void"));
		return result;
	}

}
